package root.electronclass.electronclass.other

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.os.SystemClock
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import root.electronclass.electronclass.common.adapter.CommonRecyclerViewAdapter
import root.electronclass.electronclass.common.base.BaseViewHolder
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.mvp.entity.BgData
import root.electronclass.electronclass.R
import root.electronclass.electronclass.databinding.ActivitySetBgBinding
import root.electronclass.electronclass.setup
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.VersionData
import root.electronclass.electronclass.mvp.rest.RestManager
import com.hikvision.dmb.util.InfoUtilApi
import com.jackwang.updateapk.UpdateApp
import com.jackwang.updateapk.UpdateListener
import retrofit2.Call
import root.electronclass.electronclass.mvp.GlobalParameter
import java.io.File

class SetBgActivity : ViewBindingActivity<ActivitySetBgBinding>() {


    private var mHits = LongArray(4)
    private var dialog: Dialog? = null
    private var startDialogPro: TextView? = null
    private var startDialogTv: TextView? = null

    override fun init() {
        binding.top.setup(lifecycle, "班牌背景库")
        val position = SPUtils.getInstance().getInt("bg-position", 0)
        val list = object : ArrayList<BgData>() {
            init {
                add(BgData(R.mipmap.bg1, "炫彩光感", true))
                add(BgData(R.mipmap.bg2, "深色渐变", false))
                add(BgData(R.mipmap.bg3, "蓝色几何", false))
                add(BgData(R.mipmap.bg4, "清新自然", false))
                add(BgData(R.mipmap.bg5, "朝气蓬勃", false))
                add(BgData(R.mipmap.bg6, "静谧悠闲", false))
            }
        }
        for (item in list.indices) {
            list[item].check = item == position
        }
        val adapter = object : CommonRecyclerViewAdapter<BgData>(R.layout.set_bg_item) {
            override fun convert(baseViewHolder: BaseViewHolder, item: BgData) {
                baseViewHolder.setBackgroundResources(R.id.bg_icon, item.src)
                baseViewHolder.setVisibility(
                    R.id.checked,
                    if (item.check) View.VISIBLE else View.GONE
                )
                baseViewHolder.setText(R.id.bg_tv, item.title)

                baseViewHolder.setOnClickListener(R.id.bg_item) {
                    SPUtils.getInstance().put("bg-key", item.src)
                    SPUtils.getInstance().put("bg-position", baseViewHolder.adapterPosition)
                    for (i in list.indices) {
                        list[i].check = i == baseViewHolder.adapterPosition
                    }
                    setWindowBackGround()
                    notifyDataSetChanged()
                }
            }
        }
        adapter.bindRecyclerView(binding.recycler, GridLayoutManager(this, 3))

        adapter.data = list
        adapter.notifyDataSetChanged()

        binding.back.setOnClickListener {
            setResult(Activity.RESULT_OK)
            finish()
        }
        initDialog()
        binding.version.text = getVersionName(this)
        binding.ip.text = NetworkUtils.getIPAddress(true)

        binding.version.setOnClickListener {
            continuousClick(true)
        }
    }

    private fun initDialog() {
        val view: View =
            (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(
                R.layout.download_dialog,
                null
            )
        dialog = Dialog(this@SetBgActivity, R.style.CustomDialog)
        dialog!!.addContentView(
            view,
            ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT
            )
        )
        startDialogTv = view.findViewById(R.id.start_tv)
        startDialogPro = view.findViewById(R.id.progress_tv)
    }


    /**
     * logo连点判断
     */
    private fun continuousClick(b: Boolean) {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        //为数组最后一位赋值
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - 1000) {
            mHits = LongArray(4) //重新初始化数组
            if (b) {
                downApk()
            }
        }
    }

    private fun downApk() {
        RestManager.getInstance().initRest().version()
                .enqueue(object : CallbackNext<BaseResponse<VersionData>>(mDialogViewModel) {
                    override fun onSuccessful(
                        call: Call<BaseResponse<VersionData>>?,
                        response: BaseResponse<VersionData>,
                    ) {
                        if (response.isSuccess && getVersionCode(this@SetBgActivity) < response.rows.version.toInt() &&
                                !response.rows.pkgUrl.isNullOrEmpty()) {
                            UpdateApp.getInstance().setAutoInatall(false) //是否弹起安装apk
                                    .setUpdateListener(object : UpdateListener {
                                        override fun start() {
                                            startDialogTv?.text = "开始下载"
                                            dialog?.show()
                                        }

                                        override fun progress(progress: Int) {
                                            if (dialog != null) {
                                                startDialogPro?.text = "进度：$progress"
                                            }
                                        }

                                        override fun downFinish() {
                                            if (dialog != null) {
                                                startDialogTv?.text = "下载完成"
                                                dialog?.dismiss()
                                                val path = Environment.getExternalStorageDirectory()
                                                        .toString() + File.separator + "download/app.apk"
                                                Log.i("MainActivity", "downFinish: $path")
                                                if (GlobalParameter.getEcardInfo().type == 5) {
                                                    UpdateApp.getInstance().startInstall(this@SetBgActivity)
                                                } else {
                                                    InfoUtilApi.silentInstallation(path)
                                                }
                                            }
                                        }

                                        override fun downFail(throwable: Throwable) {
                                            ToastUtil.showToast(
                                                    this@SetBgActivity,
                                                    "下载失败：" + throwable.message
                                            )
                                            if (dialog != null) {
                                                dialog?.dismiss()
                                            }
                                        }
                                    }).downloadApp(
                                            this@SetBgActivity,
                                            response.rows.pkgUrl,
                                            R.mipmap.ic_launcher,
                                            R.mipmap.ic_launcher
                                    )
                        }
                    }

                    override fun onError(
                        call: Call<BaseResponse<VersionData>>,
                        response: BaseResponse<VersionData>?,
                    ) {
                        toast(response?.msg)
                    }

                })
    }

    companion object {
        @JvmStatic
        fun startActivity(context: Context) {
            val intent = Intent(context, SetBgActivity::class.java)
            context.startActivity(intent)
        }
    }
}